var app=getApp()
var moduleUrl=app.baseUrl+'/client/reward'
Page({
  data: {
    count: 1,
    receiveType: 1, // 领取方式：1-公司领取，2-邮寄到家
    selectedAddress: null, // 选中的收货地址
    loading: true,        // 添加加载状态
    isRefreshing: false   // 添加刷新状态
  },
  onLoad(e) {
    console.log('reward:onLoad:e',e)
    this.setData({
      baseUrl:app.baseUrl,
      reward_id: e.reward_id  // 保存奖品ID，方便后续刷新使用
    })
    this.getReward(e.reward_id)
  },
  
  /**
   * 页面隐藏
   */
  onHide() {
    console.log('===== 页面隐藏 =====');
  },

  /**
   * 页面卸载
   */
  onUnload() {
    console.log('===== 页面卸载 =====');
  },
  
  /**
   * 下拉刷新触发函数
   */
  onPullDownRefresh() {
    console.log("===== 触发下拉刷新 =====");
    
    // 设置刷新状态
    this.setData({
      isRefreshing: true
    });
    
    // 刷新奖品详情
    if(this.data.reward_id) {
      this.getReward(this.data.reward_id);
    } else {
      dd.stopPullDownRefresh();
    }
  },
  
  //获取奖品详情
  getReward(reward_id){
    console.log('getReward',reward_id)
    var that = this
    
    // 设置加载状态
    this.setData({
      loading: true
    });
    
    //查出所有处于报名阶段的活动
    dd.httpRequest({
      url: moduleUrl+'/'+reward_id,
      method: 'GET',
      success: function(res) {
        console.log(moduleUrl+'/'+reward_id,res)  
        that.setData({
          reward:res.data.data,
          loading: false
        })
      },
      fail: function(res) {
        that.setData({
          loading: false
        });
        
        dd.showToast({
          type: 'fail',
          content: '数据加载失败，请重试',
          duration: 2000
        });
        
        // 记录错误
        if (app.handleError) {
          app.handleError(res, 'reward页面');
        }
      },
      complete: function(res) {
        // 停止下拉刷新动画（如果是由下拉刷新触发的）
        if (that.data.isRefreshing) {
          dd.stopPullDownRefresh();
        }
      }
    });
  },
  onDmTap(e,comp){
    console.log(e,comp)
    this.setData({
      count:e
    })
    console.log(this.data.count)
  },
  
  /**
   * 选择领取方式
   */
  selectReceiveType(e) {
    const type = parseInt(e.currentTarget.dataset.type);
    this.setData({
      receiveType: type
    });
  },
  
  /**
   * 选择收货地址
   */
  selectAddress() {
    dd.navigateTo({
      url: '/pages/address/list?from=order'
    });
  },
  
  /**
   * 确认兑换前验证
   */
  validateExchange() {
    // 如果是邮寄方式，必须选择收货地址
    if (this.data.receiveType === 2 && !this.data.selectedAddress) {
      dd.showToast({
        type: 'fail',
        content: '请选择收货地址',
        duration: 2000
      });
      return false;
    }
    return true;
  },
  
  confirmExchange(){
    // 验证兑换信息
    if (!this.validateExchange()) {
      return;
    }
    
    var that = this
    const exchangeCount = that.data.count || 1
    
    dd.confirm({
      title: '是否兑换'+that.data.reward.title,
      content: '数量:'+exchangeCount,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      success({ confirm }) {
        console.log(`用户点击了 ${confirm ? '「确定」' : '「取消」'}`);
        if(confirm==true){
          that.exchange()
        }
      },
      fail() {
        console.log('fail');
      },
      complete() {
        console.log('complete');
      },
    });
  },
  exchange(){
    var that = this
    const exchangeCount = that.data.count || 1
    
    // 构建请求数据
    const requestData = {
      count: exchangeCount,
      userId: app.userId,
      rewardId: that.data.reward.id,
      receiveType: that.data.receiveType
    };
    
    // 如果是邮寄方式，添加地址ID
    if (that.data.receiveType === 2 && that.data.selectedAddress) {
      requestData.addressId = that.data.selectedAddress.id;
    }
    
    dd.httpRequest({
      url: moduleUrl+'/exchange',
      method: 'POST',
      headers:{
        "Content-Type":"application/json"
      },
      data: JSON.stringify(requestData),
      success: function(res) {
        if(res.data.status==200){
          dd.showToast({
            type: 'success',
            content: res.data.data,
            duration: 2000
          });
        }
        else{
          dd.showToast({
            type: 'fail',
            content: res.data.message,
            duration: 2000
          });
        }
        console.log(moduleUrl+'/exchange',res)
      },
      fail: function(res) {
        // dd.alert({content: JSON.parse(res.originalData).rows'});
      },
      complete: function(res) {
        that.getReward(that.data.reward.id)
        // dd.alert({content: 'complete'});
      }
    });
  },
  
  /**
   * 页面显示时触发
   */
  onShow() {
    console.log('===== 页面显示 =====');
    
    // 获取页面栈
    const pages = getCurrentPages();
    const currPage = pages[pages.length - 1];
    
    // 如果有选中的地址，更新数据
    if (currPage.data.selectedAddress) {
      this.setData({
        selectedAddress: currPage.data.selectedAddress
      });
    }
    
    // 根据全局状态决定是否需要刷新
    if (app.globalData && app.globalData.needRefreshDetail) {
      console.log('===== 需要刷新奖品信息 =====');
      
      if(this.data.reward_id) {
        this.getReward(this.data.reward_id);
      }
      
      // 重置刷新标志
      app.globalData.needRefreshDetail = false;
    }
  }
});
